package com.xyzwps.mvckotlin.dao.repository

import com.xyzwps.mvckotlin.dao.mapper.IArticleMapper
import com.xyzwps.mvckotlin.dao.model.Article
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Repository

@Repository
class ArticleRepository(val articleMapper: IArticleMapper) {

    companion object {
        private val log = LoggerFactory.getLogger(ArticleRepository::class.java)
    }

    suspend fun getById(id: Long): Deferred<Article?> = coroutineScope {
        async {
            log.info("try to get article by id {} from db", id)
            val article = articleMapper.getById(id)
            log.info("article with id {} was {} in db", id, if (article == null) "not" else "")
            article
        }
    }

    suspend fun update(article: Article): Deferred<Article> = coroutineScope {
        async {
            articleMapper.update(article)
            article
        }
    }

    suspend fun getArticlesBeforeId(id: Long?, size: Int): Deferred<List<Article>> = coroutineScope {
        async { articleMapper.getArticlesBeforeId(id, size) ?: emptyList() }
    }

    suspend fun insert(article: Article): Deferred<Article> = coroutineScope {
        async {
            articleMapper.insert(article)
            article
        }
    }
}